/*
 * linked_list.c
 *
 * Version 1.0
 * Author: rtp
 *
 * Description: linked list
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include "linked_list.h"

//create a new list
list ll_create()
{
	list l = (list)malloc(sizeof(cell));
	l->next = NULL;
	l->content = "";
	return l;
}

//insert an element in the list
void ll_add(list l, char* value)
{
	list a;
	if(l != NULL)
	{
		a = l;
		while(a->next != NULL)
			a = a->next;

		a->next = malloc(sizeof(cell));
		a->next->next = NULL;
		a->next->content = value;
	}
}

//remove an element from the list
void ll_remove(list l, int position)
{
	int i = 0;
	list a, tmp;
	if(l == NULL)
		return;

	a = l->next;
	if(a == NULL)
		return;

	if(position == 0)
	{
		a = l;
		if(l->next == NULL)
		{
			free(a);
			l->next = NULL;
		}
		tmp = a;
		l->next = a->next;
		free(tmp);
	}

	for(i = 0; i < position - 1; i++)
	{
		if(a->next == NULL)
			return;
		a = a->next;
	}
	tmp = a->next;
	a->next = a->next->next;
	free(tmp);
}

//retrieve an element ("" if not found)
char* ll_get(list l, int position)
{
	int i = 0;
	list a;

	if(l != NULL)
	{
		if(l->next == NULL)
			return "";

		a = l->next;

		for(i = 0; i < position; i++)
		{
			if(a->next == NULL)
				return "";
			a = a->next;
		}
		return a->content;
	}
	return "";
}

//find an element in the list (-1 if not found)
int ll_find(list l, char* value)
{
	list a;
	int i = 0;
	if(l == NULL)
		return -1;

	a = l->next;

	if(a == NULL)
		return -1;

	while(a->next != NULL)
	{
		if(strcmp(a->content,value) == 0)
			return i;
		i++;
		a = a->next;
	}
	if(strcmp(a->content,value) == 0)
		return i;

	return -1;
}

//print the hole list
void ll_print(list l)
{
	list a = l;
	if(l == NULL)
		return;
	//printf("%s -> ", a->content);
	while(a->next != NULL)
	{
		a = a->next;
		printf("%s -> ", a->content);
	}
	printf("\n");
}
